package com.leecode.xiehf.page_01;

import java.util.Arrays;

/**
 * 给定一个按照升序排列的整数数组 nums，和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。
 * <p>
 * 如果数组中不存在目标值 target，返回 [-1, -1]。
 * <p>
 * 进阶：
 * <p>
 * 你可以设计并实现时间复杂度为 O(log n) 的算法解决此问题吗？
 * https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/
 */
public class Solution_0034 {

    public static void main(String[] args) {
        Solution_0034 solution = new Solution_0034();
        int[] result = solution.searchRange(
                new int[]{8}
                , 8);
        System.out.println(Arrays.toString(result));
    }

    /**
     * 二分
     *
     * @param nums
     * @param target
     * @return
     */
    public int[] searchRange(int[] nums, int target) {
        int[] result = new int[]{-1,-1};
        if (nums.length == 0) {
            return result;
        }
        getResult(nums, 0, nums.length - 1, result, target);
        return result;
    }

    private void getResult(int[] nums, int left, int right, int[] result, int target) {
        if (left > right) {
            return;
        }
        if (left == right) {
            if (nums[left] == target) {
                result[0] = left;
                result[1] = left;
            }
            return;
        }
        int mid = (left + right) / 2;
        if (nums[mid] < target) {
            getResult(nums, mid + 1, right, result, target);
        } else if (nums[mid] > target) {
            getResult(nums, left, mid - 1, result, target);
        } else {
            int l = mid;
            int r = mid;
            while (l - 1 >= left) {
                if (nums[l - 1] < target) {
                    break;
                }
                l--;
            }
            while (r + 1 <= right) {
                if (nums[r + 1] > target) {
                    break;
                }
                r++;
            }
            result[0] = l;
            result[1] = r;
        }
    }
}

